package com.aispeech.task.api.controller.base;

import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ResponseBody;

import java.beans.PropertyEditorSupport;

public class Base {
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
            @Override
            public String getAsText() {
                Object value = getValue();
                return value != null ? value.toString() : "";
            }

            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                setValue(text == null ? null : StringEscapeUtils.escapeHtml4(text.trim()));
            }
        });

        binder.setFieldMarkerPrefix(null);
    }

    @GetMapping("/healthz")
    @ResponseBody
    public String health() {
        return "OK";
    }

    protected UserDetails userDetails() {
        return (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }
}
